package com.design.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 * 基于代理实现，也就是通过AOP来对这些异常进行拦截
 * 如果抛异常了，就一起来这里进行处理
 * @ControllerAdvice: (拦截哪些controller)
 * @ResponseBody: 返回Result对象时解析成json
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * @ExceptionHandler({异常类型.class,异常类型.class})
     * @param exception 异常对象，后面获取异常信息用
     * @return 返回Result对象，既然都抓异常了，肯定就要Result.error("失败信息")
     */
    @ExceptionHandler({SQLIntegrityConstraintViolationException.class, NullPointerException.class})
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        //这里判断出来是添加员工时出现的异常
        if (exception.getMessage().contains("Duplicate entry")) {
            //exception对象分割，同时存储
            String[] splitExceptionMessage = exception.getMessage().split(" ");
            /*
              splitErrorMessage数组内存的信息
              Duplicate entry '新增的账号' for key 'idx_username'
              下标位2是新增账号，下标位5是关联的字段名
             */
            String msg = splitExceptionMessage[2] + "已存在";
            return Result.error(msg);
        }
        return Result.error("出现了未知错误");
    }

    /**
     * 删除分类异常处理方法
     * @param exception
     * @return
     */
    @ExceptionHandler({CustomException.class})
    public Result<String> exceptionHandler(CustomException exception) {
        // 直接返回异常信息
        return Result.error(exception.getMessage());
    }
}
